﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using LibCommon;
using RTCCore;

namespace LibRTC.Core.MessageMap.RegistrationStateChangeEvent
{
    public class LogInHandler : SimpleMessageHandler
    {
        private static ILogger LOGGER = LoggerFactory.GetLogger("LogInHandler", null);

        private RTCCoreClient _coreClient;

        public LogInHandler() {
            _rtcEvent = RTC_EVENT.RTCE_REGISTRATION_STATE_CHANGE;
            _name = "LogInHandler";
        }

        public void SetRTCCoreClient(RTCCoreClient client)
        {
            Debug.Assert(null != client);
            _coreClient = client;
        }

        public override void Process(RTC_EVENT rtcEventType, object rtcEvent)
        {
            Debug.Assert(RTC_EVENT.RTCE_REGISTRATION_STATE_CHANGE == rtcEventType);
            Debug.Assert(null != rtcEvent);
            Debug.Assert(rtcEvent is IRTCRegistrationStateChangeEvent);

            IRTCRegistrationStateChangeEvent registerEvent = (IRTCRegistrationStateChangeEvent) rtcEvent;

            LOGGER.LogDebug("" + registerEvent.State);

            switch (registerEvent.State) {
                
                case RTC_REGISTRATION_STATE.RTCRS_UNREGISTERING:
                    _coreClient.IPresenceUI.OnLoggingOff();
                    break;

                case RTC_REGISTRATION_STATE.RTCRS_NOT_REGISTERED:
                    _coreClient.DoDisablePresence();
                    _coreClient.IPresenceUI.OnLoggedOff();
                    break;

                case RTC_REGISTRATION_STATE.RTCRS_REGISTERING:
                    _coreClient.IPresenceUI.OnLoggingOn();
                    break;

                case RTC_REGISTRATION_STATE.RTCRS_REGISTERED:
                    _coreClient.IPresenceUI.OnLoggedOn();
                    _coreClient.ILogOnUI.LogOnSucc();
                    break;

                case RTC_REGISTRATION_STATE.RTCRS_LOGGED_OFF:
                    // The server has removed the registration for this profile. 
                    // Incoming requests are no longer forwarded.
                    _coreClient.DoLogOff();
                    _coreClient.IPresenceUI.OnLoggingOff();
                    break;

                default:
                    break;
            }

            _coreClient.RegistrationState = registerEvent.State;
        }
    }
}
